<template>
   <a-modal v-model:visible="props.visible" title="创建应用" @update:visible="handleCancel" @cancel="handleCancel">
      <template #footer>
        <a-button key="back" @click="handleCancel">取消</a-button>
        <a-button key="submit" type="primary" :loading="loading" @click="handleOk">确认</a-button>
      </template>
     <a-form ref="userFormRef"  :model="formState"  :rules="rules" >
       <a-form-item name="name" label="应用名称" >
         <a-input v-model:value="formState.name" placeholder="请输入应用名称" showCount="true" maxlength=64 />
       </a-form-item>
       <a-form-item name="descr" label="应用描述">
         <a-textarea v-model:value="formState.descr" placeholder="描述该应用的应用场景及用途" showCount="true" maxlength=256 />
       </a-form-item>
       <a-form-item label="应用图标:" name="icon">
         <a-upload
             name="file"
             :multiple="false"
             v-model:file-list="formState.iconList"
             :default-file-list="formState.iconList"
             :maxCount="1"
             :action="icon.fileUploadUrl"
             list-type="picture-card"
             :headers="icon.headers"
             :before-upload="beforeUpload"
             accept=".jpeg,.jpg,.png,.tif,.jfif,.webp,.pjp,.apng,.pjpeg,.avif,.ico,.tiff,.bmp,.xbm,.jxl,.jpeg,.svgz,.gif,.svg"
             @preview="handlePreviewPhoto"
             @download="downloadPhoto"
             @change="info => handleFileChange(info)"
             :showUploadList="{
              showDownloadIcon: true
            }"
         >
           <plus-outlined style="font-size: 28px; font-weight: 200" v-if="formState.iconList?.length == 0" />
         </a-upload>
       </a-form-item>
       <a-form-item label="选择应用类型:" name="type" v-if="!isUpdate">
         <dict-radio placeholder="请选择模板类型" v-model:value="formState.type"  dict-type-code="ai_app_type" />
       </a-form-item>
       <!-- 图标预览弹框 -->
       <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
         <img alt="example" style="width: 100%" :src="previewImage" />
       </a-modal>
     </a-form>
    </a-modal>
</template>
<script setup name="AiAppModal">
import {ref, defineComponent, reactive, onMounted} from 'vue';
import {AppApi} from "@/views/super/airag/aiapp/api/AppApi";
import {message} from "ant-design-vue";
import { FileApi, FileUploadUrl as fileUploadUrlPrefix } from '@/views/system/backend/file/api/FileApi';
import {Upload} from "ant-design-vue/es";
import {getToken} from "@/utils/token-util";
import {API_BASE_PREFIX} from "@/config/setting";


    const props = defineProps({
      visible: Boolean,
      data: Object
    });

    const rules = {
      name: [{ required: true, message: '请输入应用名称' }],
      descr: [{ required: false}]
    };

    // 是否是编辑状态
    const isUpdate = ref(false);

    const formState = ref({
      name: '',
      descr: '',
      icon: '',
      iconList: [],// 初始化为空数组
      type: ''
    });

    onMounted(async () => {
      if (props.data) {
        formState.value = { ...props.data };
        setFileList("iconList",formState.value.icon);
        isUpdate.value = true;
      } else {
        isUpdate.value = false;
      }
    });

    // 设置文件列表
    const setFileList = (name, fileId) => {
      FileApi.getAntdVInfo({ fileId: fileId }).then(res => {
        res.uid = fileId;
        formState.value[name] = [res];
      });
    };
    const emits = defineEmits(['update:visible', 'done','success']);

    // ref
    const userFormRef = ref(null);
    const loading = ref(false);

    // 图标上传预览地址
    const icon = reactive({
      // 上传文件的url
      fileUploadUrl: `${API_BASE_PREFIX}${fileUploadUrlPrefix}?secretFlag=N`,
      filePreviewUrl: `${API_BASE_PREFIX}/sysFileInfo/public/preview?fileId=`,
      // 上传文件时候要带header
      headers: {
        Authorization: getToken()
      }
    });


    // 是否展示图片预览
    const previewVisible = ref(false);
    // 图片地址
    const previewImage = ref(null);

    //上传之前的回调
    const beforeUpload = file => {
      const isJpgOrPng =
          file.type === 'image/jpeg' ||
          file.type === 'image/jpg' ||
          file.type === 'image/png' ||
          file.type === 'image/tif' ||
          file.type === 'image/jfif' ||
          file.type === 'image/webp' ||
          file.type === 'image/pjp' ||
          file.type === 'image/apng' ||
          file.type === 'image/pjpeg' ||
          file.type === 'image/avif' ||
          file.type === 'image/ico' ||
          file.type === 'image/tiff' ||
          file.type === 'image/bmp' ||
          file.type === 'image/xbm' ||
          file.type === 'image/jxl' ||
          file.type === 'image/svgz' ||
          file.type === 'image/gif' ||
          file.type === 'image/svg';
      if (!isJpgOrPng) {
        message.error('只能上传图片!');
        return Upload.LIST_IGNORE; //阻止列表展现
      }
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        message.error('图片大小不能超过5MB!');
      }
      return isJpgOrPng && isLt5M;
    };


    // 上传成功
    const handleFileChange = (info) => {
      if (info.file.status === 'done') {
        // 设置临时fileList的值
        formState.value.icon= info.file.response.data.fileId;
        message.success(`${info.file.name} 图片上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 图片上传失败`);
      }
    };

    // 点击预览图片
    const handlePreviewPhoto = async file => {
      previewImage.value = file.url || file.preview || file.thumbUrl;
      previewVisible.value = true;
    };

    //下载图片
    const downloadPhoto = file => {
      let id = file.response ? file.response.data.fileId : file.uid;
      FileApi.download({ token: getToken(), fileId: id });
    };


    const handleOk = () => {
      userFormRef.value.validate().then(async valid => {
        if (valid) {
          loading.value = true;
          // 新增操作
          AppApi.saveApp(formState.value)
              .then(async result => {
                loading.value = false;
                message.success(result.message);
                handleCancel();
                emits('done');
                if(isUpdate.value){
                  //刷新列表
                  emits('success', formState.value);
                }else{
                  //刷新列表
                  emits('success', result);
                }
              })
              .catch(() => {
                loading.value = false;
              });
        }
      });
    }

    const handleCancel = () => {
      emits('update:visible', false); // 通知父组件关闭
    };
</script>

